//https://leetcode.cn/problems/reverse-nodes-in-k-group/

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* cur = head;
        //统计有多少个节点
        int n = 0;
        while (cur)
        {
            n++;
            cur = cur->next;
        }

        //统计要几次k组翻转
        n /= k;

        //每一组逆序
        ListNode* newhead = new ListNode(0);
        ListNode* tail = newhead;
        cur = head;
        for (int i = 0; i < n; i++)
        {
            ListNode* temp = cur;
            for (int j = 0; j < k; j++)
            {
                ListNode* next = cur->next;
                cur->next = tail->next;
                tail->next = cur;
                cur = next;

            }
            tail = temp;

        }

        tail->next = cur;

        cur = newhead->next;
        delete newhead;
        return cur;

    }
};